from core.database_help import DataBaseCall
import re
from py2neo import Node, Relationship, Subgraph
dbc = DataBaseCall()

dbc.connect_neo4j()

def isValid(i):
    return type(i) == str and i

def dropEmptyDulplicate(l):
    return [i for i in set(l) if isValid(i)]

print('loding vegetable nodes.............')
veg_df = dbc.readFromExcel('corpus/veg.xlsx')
name_list =[Node('Vegetable', name=i) for i in dropEmptyDulplicate(veg_df['名称'])]
dbc.neo4j.create(Subgraph(name_list))
cate_list =[Node('VegetableCategory', name=i) for i in dropEmptyDulplicate(veg_df['类别'])]
dbc.neo4j.create(Subgraph(cate_list))

for i in veg_df.index:
    line = veg_df.loc[i]
    if isValid(line['名称']) and isValid(line['类别']):
        dbc.neo4j.run("match (v:Vegetable{name:'%s'}),(vc:VegetableCategory{name:'%s'}) create (v)-[r:BelongsTo{type:'vegetableBelongsTo'}]->(vc)"%(line['名称'],line['类别']))
    if isValid(line['名称']) and isValid(line['别名']):
        other_name_list = [i for i in dropEmptyDulplicate([i for i in re.split('[,，、.。]',line['别名'])]) if len(i) < 5]
        for other_name in other_name_list:
            dbc.neo4j.run("match (v:Vegetable{name:'%s'}) create (vv:Vegetable{name:'%s'})-[r:IsOtherNameOf]->(v)"%(line['名称'],other_name))



print('loding city nodes.............')
city_df = dbc.readFromCsv('corpus/city.csv')

city_list =[]

for i in city_df.index:
    line = city_df.loc[i]
    city_list.append(Node('City',name=line['Name'],shortName=line['ShortName'],ID=str(line['ID'])))

dbc.neo4j.create(Subgraph(city_list))

for i in city_df.index:
    line = city_df.loc[i]
    dbc.neo4j.run("match (c1:City), (c2:City) where c1.ID = '%d' and c2.ID = '%d' create (c1)-[:BelongsTo{type:'cityBelongsTo'}]->(c2)"%(line['ID'],line['ParentId']))


df = dbc.readFromCQL('match (v:Vegetable) return v')

with open('corpus/vegetable_list','w') as f:
    f.write(' '.join([i.get('name') for i in df['v']]))

df = dbc.readFromCQL('match (v:City) return v')

with open('corpus/city_list','w') as f:
    f.write(' '.join([i.get('name') for i in df['v']]))
    f.write(' ')
    f.write(' '.join([i.get('shortName') for i in df['v']]))
